package com.ruoyi.cms.controller.admin;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.cms.common.BaseController;
import com.ruoyi.cms.domain.Archives;
import com.ruoyi.cms.domain.Category;
import com.ruoyi.cms.domain.Field;
import com.ruoyi.cms.domain.Form;
import com.ruoyi.cms.domain.System;
import com.ruoyi.cms.exception.AdminGeneralException;
import com.ruoyi.cms.exception.CmsException;
import com.ruoyi.cms.exception.TransactionException;
import com.ruoyi.cms.service.*;
import com.ruoyi.cms.util.ExceptionEnum;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/cms/article")
public class ArchivesController extends BaseController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private LabelService labelService;
    @Autowired
    private FieldService fieldService;
    @Autowired
    private FormService formService;
    @Autowired
    private SystemService systemService;

    @GetMapping("/list")
    public TableDataInfo<Archives> getList(Archives params, PageQuery pageQuery) {
        return archivesService.queryListByPage(params, pageQuery);
    }

    @GetMapping("/getArchives")
    public R<Map<String,Object>> getArchives(String id,String categoryId) {
        String formId = formService.queryDefaultForm().getId();
        if(!"-1".equals(categoryId)) {
            Category category = categoryService.selectById(categoryId);
            formId = category.getFormId();
        }

        Form form = formService.queryFormById(formId);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("tableName", "system_" + form.getTableName());
        params.put("id", id);
        Map<String,Object> article = archivesService.queryArticleById(params);
        return R.ok(article);
    }

    @PostMapping(value ="/edit")
    public R<String> edit(@RequestBody Map<String,String> entity) throws CmsException {
        Archives archives = new Archives();
        archives.setId(entity.get("id"));
        archives.setTitle(entity.get("title"));
        archives.setCategoryId(entity.get("categoryId"));
        archives.setImagePath(entity.get("imagePath"));
        archives.setWeight(StringUtils.isBlank(entity.get("weight")) ? 0 : Integer.parseInt(entity.get("weight")));
        archives.setClicks(StringUtils.isBlank(entity.get("clicks")) ? 0 : Integer.parseInt(entity.get("clicks")));
        archives.setStatus(StringUtils.isBlank(entity.get("status")) ? 0 : Integer.parseInt(entity.get("status")));
        archives.setDescription(entity.get("description"));
        archives.setComment(Integer.parseInt(entity.get("comment")));
        archives.setSubscribe(Integer.parseInt(entity.get("subscribe")));
        archives.setUpdateBy(LoginHelper.getLoginUser().getLoginId());
        archives.setUpdateTime(new Date());
        //处理标签
        archives.setTag(StringUtils.isBlank(entity.get("tag")) ? "" : entity.get("tag"));
        //处理属性
        String properties = entity.get("properties");
        if(!StringUtils.isBlank(properties)){
            archives.setProperties(properties);
        }else {
            archives.setProperties(StringUtils.isNotBlank(archives.getImagePath()) ? "p" : "n");
        }

        String formId = formService.queryDefaultForm().getId();
        String categoryCode = "";
        if(!"-1".equals(entity.get("categoryId"))) {
            Category category = categoryService.selectById(archives.getCategoryId());
            categoryCode = category.getCode();
            formId = category.getFormId();
        }
        Form form = formService.queryFormById(formId);
        List<Field> fields = fieldService.queryFieldByFormId(formId);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("tableName", "system_" + form.getTableName());
        params.put("id", archives.getId());
        Map<String,Object> oldArchives = archivesService.queryArticleById(params);

        //对原有标签进行删除
        String tag = "";
        if(oldArchives!=null && oldArchives.get("tag") != null) {
            tag = oldArchives.get("tag").toString();
            if(StringUtil.isNotBlank(tag)) {
                String[] tagArr = tag.split(",");
                labelService.updateCount(tagArr);
            }
        }
        //处理新标签
        tag = archives.getTag();
        if(StringUtil.isNotBlank(tag)) {
            String[] tagArr = tag.split(",");
            labelService.insertOrUpdate(tagArr);
        }

        Map<String,Object> additional = new LinkedHashMap<String,Object>();
        for(int i = 0;i < fields.size();i++) {
            Field field = fields.get(i);
            if(StringUtil.isNotBlank(entity.get(field.getFieldName()))){
                additional.put(field.getFieldName(), entity.get(field.getFieldName()));
                //用MAP接收参数，checkbox需要特殊处理
                if("checkbox".equals(field.getDataType())) {
                    String[] arr = request.getParameterValues(field.getFieldName());
                    if(arr != null && arr.length > 0) {
                        StringBuffer checkboxVal = new StringBuffer();
                        for (String string : arr) {
                            checkboxVal.append(string + ",");
                        }
                        additional.put(field.getFieldName(), checkboxVal.substring(0, checkboxVal.length() - 1));
                    }
                }
            }
        }
        String tableName = "system_" + form.getTableName();

        try {
            archivesService.update(archives, tableName, additional, entity.get("fid"));
        } catch (TransactionException e) {
            throw new AdminGeneralException(
                ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(),
                ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage(),
                e.getMessage());
        }
        return R.ok();
    }

    @PostMapping("/save")
    public R<String> add(@RequestBody Map<String,String> entity) throws CmsException {
        Archives archives = new Archives();
        archives.setId(IdUtil.getSnowflake().nextIdStr());
        archives.setCreateTime(new Date());
        archives.setCreateBy(LoginHelper.getLoginUser().getLoginId());
        archives.setTitle(entity.get("title"));
        archives.setTag(entity.get("tag"));
        archives.setCategoryId(entity.get("categoryId"));
        archives.setCategoryIds(entity.get("categoryIds"));
        archives.setImagePath(entity.get("imagePath"));
        archives.setWeight(StringUtil.isBlank(entity.get("weight")) ? 0 : Integer.parseInt(entity.get("weight")));
        archives.setClicks(StringUtil.isBlank(entity.get("clicks")) ? 0 : Integer.parseInt(entity.get("clicks")));
        archives.setStatus(StringUtil.isBlank(entity.get("status")) ? 0 : Integer.parseInt(entity.get("status")));
        archives.setDescription(entity.get("description"));
        archives.setComment(StringUtil.isBlank(entity.get("comment")) ? 0 : Integer.parseInt(entity.get("comment")));
        archives.setSubscribe(StringUtil.isBlank(entity.get("subscribe")) ? 0 :Integer.parseInt(entity.get("subscribe")));
        //处理标签
        archives.setTag(StringUtils.isBlank(entity.get("tag")) ? "" : entity.get("tag"));
        //处理属性
        String properties = entity.get("properties");
        if(!StringUtils.isBlank(properties)){
            archives.setProperties(properties);
        }else {
            archives.setProperties(StringUtils.isNotBlank(archives.getImagePath()) ? "p" : "n");
        }

        //处理标签
        String tag = archives.getTag();
        if(StringUtil.isNotBlank(tag)) {
            String[] tagArr = tag.split(",");
            labelService.insertOrUpdate(tagArr);
        }

        if(StringUtil.isNotBlank(archives.getImagePath())) {
            if(StringUtil.isBlank(archives.getProperties())) {
                archives.setProperties("p");
            }else if(!archives.getProperties().contains("p")) {
                archives.setProperties(archives.getProperties() + ",p");
            }
        }

        //
        String formId = formService.queryDefaultForm().getId();
        String categoryCode = "";
        if(!"-1".equals(entity.get("categoryId"))) {
            Category category = categoryService.selectById(archives.getCategoryId());
            archives.setCategoryIds(category.getCatSeq());
            categoryCode = category.getCode();
            formId = category.getFormId();
        }
        Form form = formService.queryFormById(formId);
        List<Field> fields = fieldService.queryFieldByFormId(formId);
        Map<String,Object> additional = new LinkedHashMap<String,Object>();
        additional.put("id", IdUtil.getSnowflake().nextIdStr());
        additional.put("aid", archives.getId());
        for(int i = 0;i < fields.size();i++) {
            Field field = fields.get(i);
            if(StringUtil.isNotBlank(entity.get(field.getFieldName()))){
                additional.put(field.getFieldName(), entity.get(field.getFieldName()));
                //用MAP接收参数，checkbox需要特殊处理
                if("checkbox".equals(field.getDataType())) {
                    String[] arr = request.getParameterValues(field.getFieldName());
                    if(arr != null && arr.length > 0) {
                        StringBuffer checkboxVal = new StringBuffer();
                        for (String string : arr) {
                            checkboxVal.append(string + ",");
                        }
                        additional.put(field.getFieldName(), checkboxVal.substring(0, checkboxVal.length() - 1));
                    }
                }
            }
        }
        String tableName = "system_" + form.getTableName();
        try {
            archivesService.save(archives,tableName,additional);
        } catch (TransactionException e) {
            e.printStackTrace();
            throw new AdminGeneralException(
                ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(),
                ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage(),
                e.getMessage());
        }
        return R.ok();
    }
}
